<?php
namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use App\User;
use Illuminate\Support\Facades\Cache;
use App\Service\Facades\Sms;
use App\Service\Model\Agency;
use App\Service\Model\DayTotal;

class UserController extends BaseController
{
    use ThrottlesLogins;
    public function __construct()
    {
        $this->middleware('jwt:api', ['except' => ['login', 'register', 'reset_password']]);
    }


    /**
     * throttleLogin:指定username
     *
     * @return void
     */
    public function username(){
        return 'tel';
    }
    /**
     * 登录
     * 
     * @param Request $request
     * @return void
     */
    public function login(Request $request)
    {
        $rules = [
            'tel'      => 'bail|regex:/^1[34578]\d{9}$/',
            'password' => 'bail|required|between:6,15',
        ];
        $this->validate($request, $rules, [], User::attribute);
        //登录错误次数限制
        $passKey  = $this->throttleKey($request);
        if ($this->hasTooManyLoginAttempts($request)) {
            $seconds = $this->limiter()->availableIn($passKey);
            return $this->failed("输入密码错误次数过多,账户已被锁定,请等待" . $seconds . "秒后再试!");
        }
        //开始登录
        $credentials = $request->only(['tel', 'password']);
        if (!$token       = auth('api')->attempt($credentials)) {
            $this->incrementLoginAttempts($request);
            $chance = $this->limiter()->retriesLeft(
                $passKey,
                $this->maxAttempts()
            );
            return $this->failed("用户名或密码错误,你还有" . $chance . "次机会!");
        }
        

        $user   =   user();
        return $this->success([
            'tel'          => $user->tel,
            'name'         => $user->name,
            'invite_code'  => $user->invite_code,
            'user_type'    => $user->user_type, 
            'access_token' => $token,
        ]);
    }

    /**
     * 注册
     *
     * @param Request $request
     * @return void
     */
    public function register(Request $request)
    {
        $rules = [
            'tel'      => 'bail|regex:/^1[34578]\d{9}$/',
            'password' => 'bail|required|between:6,15',
            'sms_code' => 'bail|required|max:4',
            'key'      => 'bail|required'
        ];
        $this->validate($request, $rules, [], User::attribute);
        $tel         =   $request->get('tel');
        $sms_code    =   $request->get('sms_code');
        $password    =   $request->get('password');
        $key         =   $request->get('key');
      
        

        if (User::findUserByTel($tel)) {
            return $this->failed('手机号已存在');
        }

        if (!Sms::check($key , $sms_code)) {
            return $this->failed('短信验证码错误或已过期');
        }

        $agency_id   = 0;
        $level       = 0;
        $agency_name = null;
        if($request->has('invite_code')){
            $invite_code =   $request->get('invite_code');
            $agent       =   Agency::where('invite_code',$invite_code)->first();
            if(!$agent){
                return $this->failed('邀请码不存在');
            }
            $agency_id   =   $agent->getKey();
            $level       =   $agent->level;
            $agency_name =   $agent->name;
            DayTotal::incr($agency_id , 'total_register');
        }
        
        //普通用户注册
        User::create([
            'tel'           => $tel,
            'password'      => bcrypt($password),
            'parent_id'     => $agency_id,
            'agency_id'     => $agency_id,
            'agency_level'  => $level,
            'agency_name'   => $agency_name
        ]);
        
        return $this->success();
    }

    /**
     * 重置密码
     *
     * @param Request $request
     * @return void
     */
    public function reset_password(Request $request)
    {
        $rules = [
            'tel'      => 'bail|regex:/^1[34578]\d{9}$/',
            'password' => 'bail|required|between:6,15',
            'smscode'  => 'bail|required|max:4',
            'key'      => 'bail|required'
        ];
        $this->validate($request, $rules, [], User::attribute);
        $tel         =   $request->get('tel');
        $sms_code    =   $request->get('sms_code');
        $key         =   $request->get('key');
        $user        =   User::findUserByTel($tel);
        if (!$user)  return $this->failed('手机号不存在');
        if (!Sms::check($key , $sms_code)) {
            return $this->failed('短信验证码错误或已过期');
        }
        $user->password = bcrypt($request->get('password'));
        $user->save();
        return $this->success();
    }


    /**
     * 退出登录
     *
     * @return void
     */
    public function logout(){
        auth()->logout();
        return $this->success();
    }


    /**
     * 实名认证查询
     */
    public function queryUser(){
        $uid  = user()->getKey();
        $user = User::whereKey($uid)->first();
        return $this->success($user);
    }

    


}
